package com.wyg.ep_timer.controller;

import com.wyg.epcommonbase.common.ApiResult;
import com.wyg.ep_timer.feign.MailFeign;
import com.wyg.ep_timer.task.MailTask;
import com.wyg.epkafkastarter.msg.MailMsg;
import com.wyg.epkafkastarter.producer.MailProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Random;

/**
 * @Author: WangYongGan
 * @Date: 2022/5/14 20:22
 * @Description:
 */
@Api(tags = "测试")
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 注入DiscoveryClient :
     * springcloud提供的获取原数组的工具类
     * 调用方法获取服务的元数据信息
     */
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    MailFeign mailFeign;
    @Autowired
    MailTask mailTask;
    MailProducer mailProducer = MailProducer.getInstance();

    @ApiOperation("kafka")
    @GetMapping("kafka")
    public ApiResult kafka() {
        final MailMsg msg = MailMsg.builder().to("aaa").entities(Arrays.asList("a", "b", "c")).build();
        mailProducer.send(msg);
        return ApiResult.ok();
    }

    @ApiOperation("手动发送邮箱")
    @GetMapping("sendMail")
    public ApiResult sendMail() {
        mailTask.mailTask();
        return ApiResult.ok();
    }

    @ApiOperation("test")
    @GetMapping("test")
    public ApiResult test() {
        final String result = restTemplate.getForObject("http://ep-mail/test", String.class);
        return ApiResult.ok().data(result);
    }

    @ApiOperation("testByFeign")
    @GetMapping("testByFeign")
    public ApiResult testByFeign() {
        final String result = mailFeign.test();
        return ApiResult.ok().data(result);
    }

    @ApiOperation("testHystrix")
    @GetMapping("testHystrix")
    public ApiResult testHystrix() {
        Random r = new Random();
        String result = "";
        if (r.nextInt(10) > 5)
            result = mailFeign.test2();
        else result = mailFeign.test();
        return ApiResult.ok().data(result);
    }

}
